﻿using System;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Config;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Convertor;
using PlanningGIS.Util.Security;

namespace PlanningGIS.Entry
{
    /// <summary>
    /// 设置界面
    /// </summary>
    public partial class FrmSetting : Office2007Form
    {
        /// <summary>
        /// 主要是修改配置后，鹰眼图要相应做修改，所以必须调用框架的Application
        /// </summary>
        private IApplication m_Application = null; 
        /// <summary>
        /// 用来显示某些参数的枚举值的配置文件
        /// </summary>
        private string filename = AppConfig.ConfigPath + "\\enumerate.xml";
        /// <summary>
        /// 枚举根节点
        /// </summary>
        private XmlNode xmlNodeEnmu = null; 
        /// <summary>
        /// 
        /// </summary>
        private DevComponents.DotNetBar.Controls.ComboBoxEx cboEnum;
        /// <summary>
        /// 用来记录配置项中哪些节点是无需显示在界面中
        /// </summary>
        private string unvisibleFileName = AppConfig.ConfigPath + "\\unvisible.txt";
        /// <summary>
        /// 
        /// </summary>
        private List<string> unvisibleNodes;
        /// <summary>
        /// 
        /// </summary>
        private PlanningGIS.Framework.Config.SystemConfig temp;
        /// <summary>
        /// 
        /// </summary>
        private object oldValue;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        public FrmSetting(IApplication value)
        {
            InitializeComponent();
            m_Application = value;

            this.cboEnum = new DevComponents.DotNetBar.Controls.ComboBoxEx();
            this.cboEnum.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.cboEnum.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboEnum.Style = eDotNetBarStyle.StyleManagerControlled;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSetting_Load(object sender, EventArgs e)
        {
            XmlDocument xmlDocument = new XmlDocument();
            string filename = AppConfig.ConfigPath + "\\enumerate.xml";
            if (File.Exists(filename))
            {
                XmlTextReader xmlTextReader = new XmlTextReader(filename);
                xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
                xmlTextReader.MoveToContent();

                xmlDocument.Load(xmlTextReader);
                xmlTextReader.Close();
            }
            
            if (xmlDocument != null) xmlNodeEnmu = xmlDocument.SelectNodes("SystemConfig")[0];

            if (File.Exists(unvisibleFileName))
            {
                StreamReader sr = null;
                //sr = File.OpenText(unvisibleFileName);
                sr = new System.IO.StreamReader(unvisibleFileName, System.Text.Encoding.Default);

                if (!sr.EndOfStream)
                {
                    string unvisibleNode = sr.ReadLine();
                    if (unvisibleNode != "")
                    {
                        unvisibleNodes = new List<string>();
                        string[] values = unvisibleNode.Split(';');
                        unvisibleNodes = new List<string>(values);
                    }
                }
                sr.Close();
            }

            InitializeTree();
            trvSetting_NodeMouseClick(trvSetting,
                                     new TreeNodeMouseClickEventArgs(trvSetting.Nodes[0], MouseButtons.Left, 0, 0, 0));
        }

        private void InitializeTree()
        {
            trvSetting.Nodes.Clear();
            temp = AppConfig.SystemConfig;
            Type type = temp.GetType();
            FieldInfo[] fieldInfos = type.GetFields();

            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                object obj = fieldInfo.GetValue(temp);
                if (obj == null) continue;
                Type subType = obj.GetType();

                if (unvisibleNodes != null && unvisibleNodes.Contains(subType.Name)) continue;

                TreeNode tvwNode = trvSetting.Nodes.Add(subType.Name);
                tvwNode.Tag = obj;
            }
        }

        private void trvSetting_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;

            dgvxSetting.Rows.Clear();

            //因为是要移除控件，所以必须从后往前遍历
            //foreach (Control ctl in this.splitContainer1.Panel2.Controls)
            //{
            //    if (ctl is DevComponents.DotNetBar.Controls.ComboBoxEx)
            //    {
            //        this.splitContainer1.Panel2.Controls.Remove(ctl);
            //    }
            //}
            for (int i = this.splitContainer1.Panel2.Controls.Count-1; i >=0 ; i--)
            {
                Control ctl = this.splitContainer1.Panel2.Controls[i];
                if (ctl is DevComponents.DotNetBar.Controls.ComboBoxEx)
                {
                    this.splitContainer1.Panel2.Controls.Remove(ctl);
                }
            }


            if (e.Node.Tag == null) return;

            object obj = e.Node.Tag;
            Type type = obj.GetType();

            grpSetting.Text = e.Node.Text;

            XmlNode xmlNodeRoot = null;
            if (xmlNodeEnmu != null) xmlNodeRoot = xmlNodeEnmu.SelectSingleNode(e.Node.Text);

            foreach (FieldInfo pFieldInfoSub in type.GetFields())
            {
                if (pFieldInfoSub.GetValue(obj) == null) continue;

                if (unvisibleNodes != null && unvisibleNodes.Contains(pFieldInfoSub.Name)) continue;

                dgvxSetting.Rows.Add(1);
                DataGridViewRow dgvRow = dgvxSetting.Rows[dgvxSetting.Rows.Count - 1];

                dgvRow.Cells[0].Value = pFieldInfoSub.Name;

                string value = "";
                if (e.Node.Text == "数据库连接")
                {

                    //value = SecurityHelper.DeCryptConn(pFieldInfoSub.GetValue(obj).ToString(), AppConfig.SystemConfig.基本信息.加密字符串);
                }
                else
                {
                    value = (pFieldInfoSub.GetValue(obj) == null) ? "" : pFieldInfoSub.GetValue(obj).ToString();// StringUtility.ConvertWRTNull(pFieldInfoSub.GetValue(obj));
                }
                dgvRow.Cells[1].Value = value;

                XmlNode xmlNodeSub = null;
                if (xmlNodeRoot != null) xmlNodeSub = xmlNodeRoot.SelectSingleNode(pFieldInfoSub.Name);
                if (xmlNodeSub != null)
                {
                    XmlNodeList xmlNodeLst = xmlNodeSub.SelectNodes("combox");

                    ComboBoxEx comboBox = new ComboBoxEx();
                    comboBox.Style = eDotNetBarStyle.StyleManagerControlled;
                    comboBox.DrawMode = DrawMode.OwnerDrawFixed;
                    //comboBox.Dock = DockStyle.Fill;
                    comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                    //comboBox.Tag = dgvRow;

                    foreach (XmlNode xml in xmlNodeLst)
                    {
                        //combox combox = new combox();
                        //combox.value = xml.Attributes["value"].Value;
                        //combox.display = xml.Attributes["display"].Value;
                        //comboBox.Items.Add(combox);
                    }

                    if (comboBox.Items.Count > 0)
                    {
                        comboBox.SelectedIndex = 0;

                        foreach (object item in comboBox.Items)
                        {
                            //combox combox = item as combox;
                            //if (combox.value.ToUpper() == value.ToUpper())
                            //{
                            //    comboBox.Text = combox.display;
                            //    break;
                            //}
                        }

                        comboBox.Width = dgvxSetting.Columns[1].Width - 1;
                        System.Drawing.Point pPoint = new Point();
                        pPoint.X = dgvxSetting.Location.X + dgvxSetting.Columns[0].Width + 5;

                        int rowsHeight = dgvxSetting.ColumnHeadersHeight - 1;
                        for (int i = 0; i < dgvxSetting.Rows.Count; i++)
                        {
                            rowsHeight += dgvxSetting.Rows[i].Height;
                        }

                        pPoint.Y = dgvxSetting.Location.Y + rowsHeight;

                        comboBox.Location = pPoint;

                        splitContainer1.Panel2.Controls.Add(comboBox);
                        comboBox.BringToFront();

                        //comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
                        comboBox.SelectedIndexChanged += delegate(object sendercbo, EventArgs ecbo)
                        {
                            //combox combox = comboBox.SelectedItem as combox;
                            ////if (comboBox.Tag == null || !(comboBox.Tag is DataGridViewRow)) return;
                            //dgvRow.Cells[1].Value = combox.value;
                            ////(comboBox.Tag as DataGridViewRow).Cells[1].Value = combox.value;
                        };
                    }
                }
            }
            
        }

        void comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private void dgvxSetting_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == 0)
                e.Cancel = true;

            oldValue = dgvxSetting.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        }

        private void dgvxSetting_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            foreach (Control ctl in this.splitContainer1.Panel2.Controls)
            {
                if (ctl is DevComponents.DotNetBar.Controls.ComboBoxEx)
                {
                    ctl.Width = dgvxSetting.Columns[1].Width - 1;
                }
            }

        }

        private void dgvxSetting_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            ConfigHelper.SaveObject<PlanningGIS.Framework.Config.SystemConfig>(AppConfig.SystemConfig);
            
            Control control = (m_Application as IFramework).DockManager.GetControlFromDockPanel("鹰眼图");
            if (control != null)
            {
                OverViewPanel overViewPanel = control as OverViewPanel;
                overViewPanel.pEvent_OnMapReplaced(null);
            }

            Close();
        }

        private void dgvxSetting_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) return;
            if (trvSetting.SelectedNode == null) return;
            object obj = trvSetting.SelectedNode.Tag;
            if (obj == null) return;

            Type type = obj.GetType();
            FieldInfo pFieldInfo = type.GetField(dgvxSetting.Rows[e.RowIndex].Cells[0].Value.ToString());

            try
            {
                if (pFieldInfo != null)
                {
                    string value = StringHelper.ConvertWRTNull(dgvxSetting.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);

                    if (pFieldInfo.Name == "加密字符串")
                    {
                        pFieldInfo.SetValue(obj, value);

                        
                    }
                    else
                    {
                        if (pFieldInfo.FieldType == typeof(Boolean))
                        {

                            if (value != "")
                            {
                                if (value.ToUpper() == "TRUE")
                                    pFieldInfo.SetValue(obj, true);
                                else if (value.ToLower() == "FALSE")
                                    pFieldInfo.SetValue(obj, false);
                                else
                                    pFieldInfo.SetValue(obj, false);
                            }
                            else
                            {
                                pFieldInfo.SetValue(obj, false);
                            }
                        }
                        else if (pFieldInfo.FieldType == typeof(Double) || pFieldInfo.FieldType == typeof(Single))
                        {
                            if (StringHelper.CanConvert2Double(value))
                            {

                                pFieldInfo.SetValue(obj, Double.Parse(value.ToString()));
                            }
                            else
                            {
                                MsgHelper.ShowWarningMsgbox("[" + pFieldInfo.Name + "]参数应设为数值型！");
                            }
                        }
                        else if (pFieldInfo.FieldType == typeof(Decimal))
                        {
                            if (StringHelper.CanConvert2Double(value))
                            {

                                pFieldInfo.SetValue(obj, Decimal.Parse(value.ToString()));
                            }
                            else
                            {
                                MsgHelper.ShowWarningMsgbox("[" + pFieldInfo.Name + "]参数应设为数值型！");
                            }
                        }
                        else if (pFieldInfo.FieldType == typeof(Int32))
                        {
                            if (StringHelper.CanConvert2Int(value))
                            {

                                pFieldInfo.SetValue(obj, Int32.Parse(value.ToString()));
                            }
                            else
                            {
                                MsgHelper.ShowWarningMsgbox("[" + pFieldInfo.Name + "]参数应设为数值型！");
                            }
                        }
                        else if (pFieldInfo.FieldType == typeof(String))
                        {
                            pFieldInfo.SetValue(obj, value);
                        }
                        else
                        {
                            MsgHelper.ShowWarningMsgbox("[" + pFieldInfo.Name + "]参数类型无效！");
                        }


                    }
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("[" + pFieldInfo.Name + "]参数设置失败：" + ex.Message);
            }
        }

    }
}
